document.addEventListener('DOMContentLoaded', function() {
    const suggestionForm = document.getElementById('suggestionForm');
    const resetSuggestionBtn = document.getElementById('resetSuggestionBtn');
    const filterBtn = document.getElementById('filterBtn');
    const clearFilterBtn = document.getElementById('clearFilterBtn');
    const filterType = document.getElementById('filterType');
    const filterStatus = document.getElementById('filterStatus');
    const suggestionsList = document.getElementById('suggestionsList');
    const successMessage = document.getElementById('successMessage');
    
    // 初始化页面
    loadSuggestions();
    
    // 建议表单提交
    suggestionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        submitSuggestion();
    });
    
    // 重置按钮
    resetSuggestionBtn.addEventListener('click', function() {
        suggestionForm.reset();
    });
    
    // 类型和状态筛选下拉框变化时自动筛选
    filterType.addEventListener('change', filterSuggestions);
    filterStatus.addEventListener('change', filterSuggestions);

    function submitSuggestion() {
        const formData = new FormData(suggestionForm);
        const suggestionData = Object.fromEntries(formData);
        
        // 表单验证
        if (!validateSuggestionData(suggestionData)) {
            return;
        }
        
        // 创建建议对象
        const userId = localStorage.getItem('userId') || sessionStorage.getItem('userId') || null;
        const newSuggestion = {
            id: Date.now(),
            type: suggestionData.suggestionType, // 这里的suggestionType应直接为中文
            priority: suggestionData.priority,   // 这里的priority应直接为中文
            title: suggestionData.suggestionTitle,
            content: suggestionData.suggestionContent,
            contactInfo: suggestionData.contactInfo || '',
            status: '待处理', // 直接用中文
            user_id: userId ? Number(userId) : null,
            submitter: '匿名用户',
            submitTime: getMySQLDateTimeString(new Date()),
            votes: 0
        };
        
        // 保存建议到localStorage
        const suggestions = JSON.parse(localStorage.getItem('suggestions') || '[]');
        suggestions.push(newSuggestion);
        localStorage.setItem('suggestions', JSON.stringify(suggestions));
        
        // 显示成功消息
        showSuccessMessage();

        // 提交建议到后端
        fetch('http://localhost:3000/api/suggestions', {
            method: 'POST',
            headers: {
                'Authorization': sessionStorage.getItem('token') || '',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content: newSuggestion.content,
                user_id: newSuggestion.user_id,
                title: newSuggestion.title,
                type: newSuggestion.type,
                priority: newSuggestion.priority,
                status: newSuggestion.status,
                contact_info: newSuggestion.contactInfo,
                submitter: newSuggestion.submitter,
                submit_time: newSuggestion.submitTime,
                votes: newSuggestion.votes
            })
        })
        .then(response => response.json().then(data => ({status: response.status, data})))
        .then(({status, data}) => {
            if (status === 200 && data.message) {
                showCenterModal(data.message || '建议提交成功！');
                loadSuggestions();
            } else {
                showCenterModal(data.error || '建议提交失败！');
            }
        })
        .catch(error => {
            showCenterModal('建议提交失败！');
            console.error('建议提交失败:', error);
        });
    }
    
    function validateSuggestionData(data) {
        if (!data.suggestionType) {
            showCenterModal('请选择建议类型！');
            return false;
        }
        
        if (!data.priority) {
            showCenterModal('请选择紧急程度！');
            return false;
        }
        
        if (!data.suggestionTitle || data.suggestionTitle.trim().length === 0) {
            showCenterModal('请输入建议标题！');
            return false;
        }
        
        if (!data.suggestionContent || data.suggestionContent.trim().length === 0) {
            showCenterModal('请输入详细描述！');
            return false;
        }
        
        if (data.suggestionContent.trim().length < 10) {
            showCenterModal('详细描述至少需要10个字符！');
            return false;
        }
        
        return true;
    }
    
    function loadSuggestions() {
        fetch('http://localhost:3000/api/suggestions', {
            headers: { 'Authorization': sessionStorage.getItem('token') || '' }
        })
        .then(res => res.json())
        .then(data => {
            if (Array.isArray(data)) {
                // 兼容后端字段名
                const suggestions = data.map(item => ({
                    id: item.id,
                    type: item.type,
                    priority: item.priority,
                    title: item.title,
                    content: item.content,
                    contactInfo: item.contact_info,
                    status: item.status,
                    submitter: item.submitter || '匿名用户',
                    submitTime: item.submit_time || item.created_at,
                    votes: item.votes || 0,
                    voted: item.voted || false // 新增
                }));
                window.allSuggestions = suggestions;
                displaySuggestions(suggestions);
            } else {
                const suggestions = JSON.parse(localStorage.getItem('suggestions') || '[]');
                window.allSuggestions = suggestions;
                displaySuggestions(suggestions);
            }
        })
        .catch(() => {
            const suggestions = JSON.parse(localStorage.getItem('suggestions') || '[]');
            window.allSuggestions = suggestions;
            displaySuggestions(suggestions);
        });
    }
    
    function displaySuggestions(suggestions) {
        if (suggestions.length === 0) {
            suggestionsList.innerHTML = '<p class="no-suggestions">暂无建议</p>';
            return;
        }
        
        // 按提交时间倒序排列
        suggestions.sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
        
        let html = '';
        const isAdmin = sessionStorage.getItem('role') === 'admin'; // 判断是否管理员
        // 类型/优先级class映射
        const typeClassMap = {
            '功能改进': 'function',
            '数据结构': 'data',
            '界面优化': 'ui',
            '性能优化': 'performance',
            '其他建议': 'other'
        };
        const priorityClassMap = {
            '很紧急': 'high',
            '一般': 'medium',
            '不紧急': 'low'
        };
        suggestions.forEach(suggestion => {
            html += `
                <div class="suggestion-item">
                    <div class="suggestion-header">
                        <h4 class="suggestion-title">${suggestion.title}</h4>
                        <span class="status-badge status-${suggestion.status}">${getStatusName(suggestion.status)}</span>
                    </div>
                    <div class="suggestion-meta">
                        <span class="suggestion-type type-${typeClassMap[suggestion.type] || 'other'}">${getTypeName(suggestion.type)}</span>
                        <span class="priority-badge priority-${priorityClassMap[suggestion.priority] || 'medium'}">${getPriorityName(suggestion.priority)}</span>
                        <span>提交者: ${suggestion.submitter}</span>
                        <span>提交时间: ${formatDate(suggestion.submitTime)}</span>
                        <span>投票: ${suggestion.votes}</span>
                    </div>
                    <div class="suggestion-content">${suggestion.content}</div>
                    ${suggestion.contactInfo ? `<div class="suggestion-contact">联系方式: ${suggestion.contactInfo}</div>` : ''}
                    <div class="suggestion-footer">
                        <div class="suggestion-actions">
                            <button class="btn btn-primary btn-sm vote-btn" data-id="${suggestion.id}" ${suggestion.voted ? 'disabled style="background:#bbb;cursor:not-allowed;"' : ''}>投票</button>
                            ${isAdmin ? `<select class='status-select' data-id='${suggestion.id}' style='margin-left:10px;'>
                                <option value=''>处理建议</option>
                                <option value='待处理'>待处理</option>
                                <option value='审核中'>审核中</option>
                                <option value='已采纳'>已采纳</option>
                                <option value='已拒绝'>已拒绝</option>
                            </select>` : ''}
                        </div>
                        <span>建议ID: ${suggestion.id}</span>
                    </div>
                </div>
            `;
        });
        
        suggestionsList.innerHTML = html;
        // 投票按钮事件绑定
        document.querySelectorAll('.vote-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                fetch(`http://localhost:3000/api/suggestions/${id}/vote`, {
                    method: 'POST',
                    headers: {
                        'Authorization': sessionStorage.getItem('token') || '',
                        'Content-Type': 'application/json'
                    }
                })
                .then(res => res.json())
                .then(data => {
                    showCenterModal(data.message || '投票成功');
                    loadSuggestions();
                })
                .catch(() => showCenterModal('投票失败'));
            });
        });
        // 管理员处理建议事件绑定
        if (isAdmin) {
            document.querySelectorAll('.status-select').forEach(sel => {
                sel.addEventListener('change', function() {
                    const id = this.getAttribute('data-id');
                    const status = this.value;
                    if (!status) return;
                    showCenterConfirm('确定要将该建议状态修改为“' + getStatusName(status) + '”吗？', function(ok) {
                        if (!ok) return;
                        fetch(`http://localhost:3000/api/suggestions/${id}`, {
                            method: 'PATCH',
                            headers: {
                                'Authorization': sessionStorage.getItem('token') || '',
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ status })
                        })
                        .then(res => res.json())
                        .then(data => {
                            showCenterModal(data.message || '状态更新成功');
                            loadSuggestions();
                        })
                        .catch(() => showCenterModal('状态更新失败'));
                    });
                });
            });
        }
    }
    
    function filterSuggestions() {
        const typeFilter = filterType.value;
        const statusFilter = filterStatus.value;
        let filteredSuggestions = window.allSuggestions || [];
        if (typeFilter) {
            filteredSuggestions = filteredSuggestions.filter(s => s.type === typeFilter);
        }
        if (statusFilter) {
            filteredSuggestions = filteredSuggestions.filter(s => s.status === statusFilter);
        }
        displaySuggestions(filteredSuggestions);
    }
    
    function getTypeName(type) {
        // 直接返回type（已是中文）
        return type;
    }
    
    function getPriorityName(priority) {
        return priority;
    }
    
    function getStatusName(status) {
        return status;
    }
    
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    function showSuccessMessage() {
        suggestionForm.style.display = 'none';
        successMessage.style.display = 'block';
    }
    
    // 屏幕中心弹窗
    function showCenterModal(message, callback) {
        let modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.left = '0';
        modal.style.top = '0';
        modal.style.width = '100vw';
        modal.style.height = '100vh';
        modal.style.background = 'rgba(0,0,0,0.18)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9999';
        modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:320px;text-align:center;\">
            <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
            <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
            <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
        </div>`;
        document.body.appendChild(modal);
        document.getElementById('centerModalBtn').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback();
        };
    }
    
    // 全局函数供HTML调用
    window.voteSuggestion = function(suggestionId) {
        // 模拟投票功能
        showCenterModal(`已为建议 ${suggestionId} 投票！`);
    };
    
    window.viewSuggestion = function(suggestionId) {
        // 模拟查看详情功能
        showCenterModal(`查看建议 ${suggestionId} 的详细信息`);
    };

    // 新增：格式化为 MySQL DATETIME 字符串
    function getMySQLDateTimeString(date) {
        return date.getFullYear() + '-' +
            String(date.getMonth() + 1).padStart(2, '0') + '-' +
            String(date.getDate()).padStart(2, '0') + ' ' +
            String(date.getHours()).padStart(2, '0') + ':' +
            String(date.getMinutes()).padStart(2, '0') + ':' +
            String(date.getSeconds()).padStart(2, '0');
    }
}); 

// 在文件末尾添加绿色主题的showCenterConfirm函数
function showCenterConfirm(message, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `
        <div style="background:#fff;border-radius:14px;box-shadow:0 6px 32px #388e3c22;padding:36px 40px;min-width:360px;text-align:center;">
            <div style="font-size:22px;font-weight:700;margin-bottom:14px;color:#388e3c;">提示</div>
            <div style="font-size:17px;margin-bottom:28px;color:#222;">${message}</div>
            <button id="centerConfirmOk" style="background:#4caf50;color:#fff;border:none;border-radius:7px;padding:10px 38px;font-size:17px;cursor:pointer;margin-right:18px;transition:background 0.2s;">确定</button>
            <button id="centerConfirmCancel" style="background:#eee;color:#388e3c;border:none;border-radius:7px;padding:10px 38px;font-size:17px;cursor:pointer;transition:background 0.2s;">取消</button>
        </div>
    `;
    document.body.appendChild(modal);
    document.getElementById('centerConfirmOk').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback(true);
    };
    document.getElementById('centerConfirmCancel').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback(false);
    };
    // 按钮悬停效果
    document.getElementById('centerConfirmOk').onmouseover = function() {
        this.style.background = '#388e3c';
    };
    document.getElementById('centerConfirmOk').onmouseout = function() {
        this.style.background = '#4caf50';
    };
    document.getElementById('centerConfirmCancel').onmouseover = function() {
        this.style.background = '#c8e6c9';
    };
    document.getElementById('centerConfirmCancel').onmouseout = function() {
        this.style.background = '#eee';
    };
} 